<script setup>
import { ref, getCurrentInstance, onMounted, reactive } from 'vue'
import { ElMessage, dayjs } from 'element-plus'

import utc from 'dayjs/plugin/utc'
import duration from 'dayjs/plugin/duration'
dayjs.extend(utc)
dayjs.extend(duration)

const internalInstance = getCurrentInstance()
let electron = null
if (window.electron) {
  electron = window.electron
}
console.warn(electron, internalInstance)
let columns = ref([])
let tableData = ref([])
let total = ref(0)
let pageIndex = ref(1)
let pageSize = ref(100)
let loading = ref(false)

// 渠道商ID
// let ditchIds = ref([])

// 表单查询
let formInline = reactive({
  equipmentId: '',
  deviceId: '',
  proxyIp: '',
  status: 1,
  createdAt: dayjs().format('YYYY-MM-DD HH:mm:ss')
})

columns.value.push(
  ...[
    {
      align: 'center',
      width: '80',
      show: true,
      fixed: false,
      prop: 'id',
      label: '序号'
    },
    {
      align: 'center',
      show: true,
      fixed: false,
      prop: 'deviceId',
      label: '设备Id'
    },
    {
      align: 'center',
      show: true,
      fixed: false,
      prop: 'token',
      label: '账号'
    },
    {
      align: 'center',
      show: true,
      width: '100',
      fixed: false,
      prop: 'status',
      label: '状态'
    },
    {
      align: 'center',
      show: true,
      prop: 'proxyIp',
      label: '代理IP'
    },
    {
      align: 'center',
      show: true,
      prop: 'createdAt',
      label: '创建时间'
    },
    {
      align: 'center',
      width: '300',
      show: true,
      prop: 'operation',
      label: '操作'
    }
  ]
)

/**
 *
 * @returns 获取代理IP列表
 *
 */

let proxyipLst = ref([])
async function getProxyIpList() {
  let proxyapi = `http://208.87.207.213/proxyIp2.txt`
  const response_ = await fetch(proxyapi, {
    method: 'GET',
    body: undefined
  })
  let response = await response_.text()
  if (response.includes('ERROR')) {
    ElMessage({
      type: 'error',
      message: response
    })
    return
  }
  if (response) {
    let text = response.split('\r\n')
    let obj = []
    for (const iterator of text) {
      if (iterator) {
        let IpInfo = iterator.split(':')
        obj.push({
          ip: IpInfo[0] + ':' + IpInfo[1],
          auth: IpInfo[2] + ':' + IpInfo[3]
        })
      }
    }
    let randomList = getRandomElements(obj, obj.length)
    proxyipLst.value = randomList
  } else {
    proxyipLst.value = []
  }
}

function getRandomElements(arr, n) {
  let tmpArr = JSON.parse(JSON.stringify(arr))
  let result = new Array(n),
    len = tmpArr.length,
    taken = new Array(len)
  if (n > len) throw new RangeError('getRandomElements: input array is not long enough.')
  while (n--) {
    var x = Math.floor(Math.random() * len)
    result[n] = tmpArr[x in taken ? taken[x] : x]
    taken[x] = --len in taken ? taken[len] : len
  }
  return result
}

/**
 *
 * @returns 获取账号设备信息列表
 *
 */
async function getDevicesAccountList() {
  loading.value = true
  await new Promise((resolve) => {
    setTimeout(() => {
      resolve(true)
    }, 100)
  })
  let DouYionEquipment = `http://208.87.207.213:38390/DevicesAccount/DevicesAccountList?sgin=47CFD0A2EB7EA1DC043F1B91926890E9&page=${pageIndex.value}&pageNo=${pageSize.value}`
  // if (formInline.createdAt) {
  //   DouYionEquipment += `&createdAt=${dayjs(formInline.createdAt).format('YYYY-MM-DD HH:mm:ss')}`
  // } else {
  //   DouYionEquipment += `&createdAt=${dayjs().format('YYYY-MM-DD HH:mm:ss')}`
  // }
  if (formInline.deviceId) {
    DouYionEquipment += `&deviceId=${formInline.deviceId}`
  }
  if (formInline.proxyIp) {
    DouYionEquipment += `&proxyIp=${formInline.proxyIp}`
  }
  if (formInline.status) {
    DouYionEquipment += `&status=${formInline.status}`
  }
  const response_ = await fetch(DouYionEquipment, {
    method: 'GET',
    headers: {
      'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    body: undefined
  })
  let response = await response_.json()
  loading.value = false
  console.warn(response.data)
  total.value = response.data.count
  tableData.value = response.data.rows
}

/**
 *
 * @returns 新增账号设备信息
 *
 */
async function DevicesAccountadd(SendData) {
  loading.value = true
  let DouYionEquipment = `http://208.87.207.213:38390/DevicesAccount/DevicesAccountadd`
  const response_ = await fetch(DouYionEquipment, {
    method: 'POST',
    headers: {
      'content-type': 'application/json; charset=UTF-8'
    },
    body: JSON.stringify({
      sgin: '47CFD0A2EB7EA1DC043F1B91926890E9',
      SendData: JSON.stringify(SendData)
    })
  })
  let response = await response_.json()
  console.warn(response)
  loading.value = false
  if (response.code != 200) {
    ElMessage({
      type: 'error',
      message: '初始化数据失败!' + (response.mes || '')
    })
    return
  }
  await getDevicesAccountList()
}

// 设备账号检测
async function CheckDevicesAccoun(data, type) {
  console.warn(data, type)
}

/**
 *
 * @returns 获取账号设备信息删除
 *
 */
async function DevicesAccounDelete(data) {
  try {
    loading.value = true
    await new Promise((resolve) => {
      setTimeout(() => {
        resolve(true)
      }, 100)
    })
    let DouYionEquipment = `http://208.87.207.213:38390/DevicesAccount/DevicesAccountDelete`
    // const SendData = {}
    const response_ = await fetch(DouYionEquipment, {
      method: 'POST',
      headers: {
        'content-type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify({
        sgin: '47CFD0A2EB7EA1DC043F1B91926890E9',
        id: data.id
      })
    })
    let response = await response_.json()
    loading.value = false
    console.warn(response)
    if (response.code != 200) {
      ElMessage({
        type: 'error',
        message: '操作失败!' + response.msg
      })
      return
    }
    ElMessage({
      type: 'success',
      message: '删除成功!'
    })
    await getDevicesAccountList()
  } catch (error) {
    loading.value = false
  }
}

onMounted(async () => {
  // let ditchIds_ = localStorage.getItem('ditchIds')
  // if (ditchIds_) {
  //   ditchIds.value = JSON.parse(ditchIds_)
  // }
  getProxyIpList()
  getDevicesAccountList()
})

async function handleCurrentChange(number) {
  console.warn('handleCurrentChange', number)
  pageIndex.value = number
  await getDevicesAccountList()
}

/**
 *
 * 进入直播间wss地址
 *
 */

// 每几个账号使用一个IP
let AccountIpNumber = ref(3)
// 账号类型
let OnlineType = ref(3)

/**
 * 初始化数据
 * @param {*}
 */
async function Initialization() {
  let data = await getLiveRoomUrl()
  await DevicesAccountadd(data)
}

/**
 * 清空数据表
 */
async function truncateData() {
  let DouYionEquipment = `http://208.87.207.213:38390/DevicesAccount/DevicesAccountDelete`
  // const SendData = {}
  const response_ = await fetch(DouYionEquipment, {
    method: 'POST',
    headers: {
      'content-type': 'application/json; charset=UTF-8'
    },
    body: JSON.stringify({
      sgin: '47CFD0A2EB7EA1DC043F1B91926890E9',
      truncate: true
    })
  })
  let response = await response_.json()
  loading.value = false
  console.warn(response)
  if (response.code != 200) {
    ElMessage({
      type: 'error',
      message: '操作失败!' + response.msg
    })
    return
  }
  ElMessage({
    type: 'success',
    message: '清除数据成功!'
  })
  await getDevicesAccountList()
}

async function getLiveRoomUrl() {
  let HuoShanTokenList = []
  let DeviceList = []
  let RoomUrlList = []
  // 已经开始的
  if (OnlineType.value == 2) {
    let HuoShanToken = localStorage.getItem('HuoShanTokenList')
    if (!HuoShanToken) {
      ElMessage({
        type: 'error',
        message: '没有可账号数据!'
      })
      return
    }
    let tmp = JSON.parse(HuoShanToken).rows
    HuoShanTokenList = tmp
  }
  if (OnlineType.value == 3) {
    let TokenList = localStorage.getItem('TokenList')
    if (!TokenList) {
      ElMessage({
        type: 'error',
        message: '没有可账号数据!'
      })
      return
    }
    let tmp2 = JSON.parse(TokenList)
    HuoShanTokenList = tmp2
  }
  let DouyinAccountList = localStorage.getItem('DouyinAccountList')
  if (!DouyinAccountList) {
    ElMessage({
      type: 'error',
      message: '没有可设备数据!'
    })
    return
  }
  let ipNumber = 0
  DeviceList = JSON.parse(DouyinAccountList).rows
  for (let index = 0; index < HuoShanTokenList.length; index++) {
    if (index % AccountIpNumber.value == 0) {
      ipNumber += 1
    }
    console.warn(proxyipLst.value[ipNumber])
    const element = DeviceList[index]
    let login_params = element.login_params
    // 设备对象信息
    let deviceInfo = {}
    // 设备整体数据解析
    let arr = login_params.split('ws_apps=')
    arr[0] = arr[0] + 'ws_apps='
    // 第一段数据截取 包含 mac_addr device_id
    let device_a = arr[0].split('#')
    // 第二段数据截取
    let device_b_arr = arr[1].split('#')
    // 包含手机信息  channel_id app_id mcc_mnc等 类型 对象数组字符串
    let device_c = device_b_arr[0]
    // 包含 device_token= dr_channel cookie
    let device_d = device_b_arr.slice(1, -1)

    // console.warn('device_a--->>', device_a)
    for (const iterator of device_a) {
      let sarr = iterator.split('=')
      deviceInfo[sarr[0]] = sarr[1]
    }
    // console.warn('device_b_arr--->>', device_b_arr)
    // console.warn('device_c--->>', JSON.parse(device_c))
    let jsonc = {}
    try {
      jsonc = JSON.parse(device_c)
    } catch (error) {
      jsonc = JSON.parse(device_c.replaceAll('\\', ''))
    }
    let device_c_extra = device_c ? jsonc[0].extra.split('&') : []
    let extra = {}
    for (const iterator of device_c_extra) {
      let sarr = iterator.split('=')
      extra[sarr[0]] = sarr[1]
    }
    deviceInfo = Object.assign(deviceInfo, device_c ? jsonc[0] : {})
    deviceInfo.extra = extra
    // console.warn('device_d--->>', device_d)
    for (const iterator of device_d) {
      let sarr = iterator.split('=')
      deviceInfo[sarr[0]] = sarr[1]
    }
    console.warn(deviceInfo)
    let newtime = new Date().getTime()
    let channel = deviceInfo['extra']['channel'] || ''
    let device_type = deviceInfo['extra']['device_type'] || ''
    let room_id = ''
    let resolution = deviceInfo['extra']['resolution'] || ''
    let cdid = deviceInfo['extra']['cdid'] || ''
    let device_id = deviceInfo['extra']['device_id'] || ''
    let token = HuoShanTokenList[index] ? HuoShanTokenList[index].x_tt_token : ''
    let _rticket = newtime
    let iid = deviceInfo['extra']['iid'] || ''
    let openudid = deviceInfo['extra']['openudid'] || ''
    let sessionId = ''
    if (HuoShanTokenList[index] && HuoShanTokenList[index].x_tt_token) {
      sessionId = HuoShanTokenList[index].x_tt_token.slice(2, 34)
    }
    let oaid = '9e6340801d21ffa3'
    let dpi = deviceInfo['extra']['dpi'] || ''
    let device_brand = deviceInfo['extra']['device_brand'] || ''
    let os_version = deviceInfo['extra']['os_version'] || '9'
    let version_name = deviceInfo['extra']['version_name'] || '20.7.0'
    let user_id = HuoShanTokenList[index] ? HuoShanTokenList[index].user_id_str : '0'
    let version_code = deviceInfo['extra']['version_code'] || '200700'
    let update_version_code = deviceInfo['extra']['update_version_code'] || '20709900'
    let manifest_version_code = deviceInfo['extra']['manifest_version_code'] || '200701'
    let host_abi = deviceInfo['extra']['host_abi'] || 'armeabi-v7a'
    let ts = parseInt(_rticket / 1000)
    let aid = deviceInfo['extra']['aid'] ? parseInt(deviceInfo['extra']['aid']) : 1128
    let access_key = api.md5('9e1bd35ec9db7b8d846de66ed140b1ad9' + device_id + 'f8a69f1719916z') //转换MD5
    let live_room_url = `wss://webcast100-ws-c.amemv.com/webcast/im/push/v2/?is_guest_mode=0&app_type=normal&room_tag=video&channel=${channel}&is_android_pad=0&device_type=${device_type}&language=zh&cpu_support64=true&live_cursor=0&rid=${room_id}&resolution=${resolution}&update_version_code=${update_version_code}&im-sdk-version=2&cdid=${cdid}&minor_status=0&need_persist_msg_count=12&parse_cnt=0&ac=wifi&package=com.ss.android.ugc.aweme&current_network_quality_info=%7B%7D&device_id=${device_id}&compress=gzip&recv_cnt=0&version_code=${version_code}&support_cache=1&im-x-tt-token=${token}&resp_content_type=protobuf&live_id=1&address_book_access=2&user_id=${user_id}&device_platform=android&aid=${aid}&cursor=0&room_id=${room_id}&last_rtt=0&manifest_version_code=${manifest_version_code}&_rticket=${_rticket}&webcast_gps_access=1&iid=${iid}&is_landscape=false&host_abi=${host_abi}&openudid=${openudid}&sid=${sessionId}&is_pad=false&appTheme=light&os_api=28&identity=audience&webcast_locale=zh_CN&dpi=${dpi}&oaid=${oaid}&carrier_region=CN&os=android&os_version=${os_version}&support_wrds=1&webcast_sdk_version=2650&app_name=aweme&version_name=${version_name}&device_brand=${device_brand}&need_personal_recommend=1&webcast_language=zh&ts=${ts}&which_ws=live_ws&version_code=${version_code}&iid=${iid}&platform=0&fpid=9&sdk_version=2&transport_mode=0&device_id=${device_id}&service_id_list=%5B%5D&private_protocol_enable=false&aid=${aid}&ttnet_ignore_offline=1&access_key=${access_key}&ne=1`
    RoomUrlList.push({
      status: 1,
      deviceId: device_id,
      token: token,
      wss: live_room_url,
      proxyIp: proxyipLst.value[ipNumber]
        ? proxyipLst.value[ipNumber].ip +
          '==' +
          (proxyipLst.value[ipNumber] ? proxyipLst.value[ipNumber].auth : '')
        : ''
    })
  }
  return RoomUrlList
}
</script>

<template>
  <div class="container no-drag">
    <div class="search">
      <el-form ref="queryForm" :inline="true" :model="formInline">
        <el-form-item label="设备Id：">
          <el-input v-model="formInline.deviceId" placeholder="请输入设备Id" />
        </el-form-item>
        <el-form-item label="设备账号状态：">
          <el-select v-model="formInline.status" class="m-2" placeholder="请选择设备渠道">
            <el-option
              v-for="(item, index) in [
                { label: '未使用', value: 1 },
                { label: '正在使用', value: 2 },
                { label: '冷却中', value: 3 }
              ]"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="代理IP：">
          <el-input v-model="formInline.proxyIp" placeholder="请输入代理IP" />
        </el-form-item>
        <el-form-item label="任务创建时间：">
          <el-input
            v-model="formInline.createdAt"
            :value="formInline.createdAt"
            type="datetime-local"
            placeholder="请选择时间"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getDevicesAccountList">查询</el-button>
        </el-form-item>
        <el-form-item>
          <div class="total_tatistics">
            <span>每个{{ AccountIpNumber }}个账户号使用1个IP： </span>
            <el-input-number v-model="AccountIpNumber" style="width: 100px"></el-input-number>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="Initialization">初始化数据</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="truncateData">清空数据</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="table"
      v-loading="loading"
      :data="tableData"
      empty-text="暂无数据"
      border
      row-key="id"
      size="large"
      stripe
      style="width: 100%"
      height="700"
      highlight-current-row
      :header-cell-style="{ background: '#F9F9F9', color: '#606266' }"
    >
      <el-table-column
        v-for="(item, index) in columns"
        :key="index"
        :align="item.align"
        :show-overflow-tooltip="true"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
        :fixed="item.fixed"
      >
        <template #default="scope">
          <div v-if="item.prop == 'live_url'">
            <el-link type="primary" @click="_blank_page(scope.row[item.prop])">{{
              scope.row[item.prop]
            }}</el-link>
          </div>
          <div v-else-if="item.prop == 'id'">
            {{ scope.$index + 1 }}
          </div>
          <div v-else-if="item.prop == 'status'">
            <el-link v-if="scope.row[item.prop] == 1" type="primary">未使用</el-link>
            <el-link v-if="scope.row[item.prop] == 2" type="success">正在使用</el-link>
            <el-link v-if="scope.row[item.prop] == 3" type="success">冷却中</el-link>
          </div>
          <div v-else-if="item.prop == 'operation'">
            <el-button size="small" type="primary" @click="CheckDevicesAccoun(scope.row, 1)"
              >账号检测</el-button
            >
            <el-button size="small" type="primary" @click="CheckDevicesAccoun(scope.row, 2)"
              >账号检测</el-button
            >
            <el-button size="small" type="danger" @click="DevicesAccounDelete(scope.row)"
              >删除设备账号</el-button
            >
          </div>
          <div v-else>{{ scope.row[item.prop] }}</div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 合计统计显示 -->
    <div class="total_tatistics">
      <span>总设备账号数：{{ total || '0' }} </span>
      <span style="margin-left: 10px">当前页获取设备账号数量：{{ tableData.length || '0' }} </span>
      <span style="margin-left: 10px">当页展示设备账号数：{{ tableData.length || '0' }} </span>
    </div>
    <div class="pagination">
      <el-pagination
        :current-page="pageIndex"
        layout=" prev, pager, next"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="total"
        background
        prev-text="上一页"
        next-text="下一页"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style lang="less">
.tablebox {
  table tbody {
    display: block;
    height: 200px;
    overflow-y: scroll;
  }

  table thead,
  tbody tr {
    display: table;
    width: 100%;
    table-layout: fixed;
  }

  .left .el-tooltip__popper,
  .right .el-tooltip__popper {
    padding: 8px 10px;
  }
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.total_tatistics {
  padding: 12px;
  font-family: auto;
  font-size: 15px;
  font-weight: bold;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 19px;
}
</style>
